package com.tbit.uqbike.service.business.impl;

import cn.hutool.core.io.FileUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tbit.uqbike.object.pojo.dto.BalanceDTO;
import com.tbit.uqbike.object.pojo.dto.BalanceDownloadDTO;
import com.tbit.uqbike.object.pojo.dto.BalancePageDTO;
import com.tbit.uqbike.object.pojo.vo.TotalBalanceVO;
import com.tbit.uqbike.object.pojo.vo.UserBalanceVO;
import com.tbit.common.entity.view.PageResult;
import com.tbit.uqbike.service.business.UserBalanceStatService;
import com.tbit.uqbike.webmanager.dao.core.SubAccountDao;
import com.tbit.uqbike.webmanager.util.BeanUtils;
import com.tbit.uqbike.webmanager.util.csv.CsvExportUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;
import java.util.UUID;

@Service
public class UserBalanceStatServiceImpl implements UserBalanceStatService {

    @Autowired
    CsvExportUtils csvExportUtils;
    @Autowired
    private SubAccountDao subAccountDao;

    @Override
    public TotalBalanceVO getTotalBalance(BalanceDTO balanceDTO) {
        return subAccountDao.getTotalBalance(balanceDTO);
    }

    @Override
    public PageResult<UserBalanceVO> getBalancePage(BalancePageDTO dto) {
        BalanceDTO balanceDTO = BeanUtils.copyProperties(dto, BalanceDTO.class);
        PageHelper.startPage(dto.getPageNO(), dto.getRowCount());
        List<UserBalanceVO> list = subAccountDao.getBalanceList(balanceDTO);
        PageInfo<UserBalanceVO> pageInfo = new PageInfo(list);
        return new PageResult<>(dto.getPageNO(), dto.getRowCount(), pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getList());
    }

    @Override
    public String download(BalanceDownloadDTO downloadDTO) {
        //获取临时路径
        File tempFile = csvExportUtils.getTempFile();
        try {
            File file = download(downloadDTO, tempFile);
            String uploadFileName = UUID.randomUUID().toString().replaceAll("-", "");
            //压缩上传oss
            return csvExportUtils.uploadZip(tempFile, uploadFileName, file);
        } finally {
            //删除本地文件
            FileUtil.del(tempFile);
        }
    }

    public File download(BalanceDownloadDTO downloadDTO, File tempFile) {
        BalanceDTO balanceDTO = BeanUtils.copyProperties(downloadDTO, BalanceDTO.class);
        List<UserBalanceVO> list = subAccountDao.getBalanceList(balanceDTO);
        File file = csvExportUtils.exportCsv(UserBalanceVO.class, tempFile, downloadDTO.getFileName(), list);
        return file;
    }

}
